package com.amumu.drama.common.modules.yipay.service.impl;

import cn.hutool.core.lang.TypeReference;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.amumu.drama.common.modules.sumapay.dto.req.WeChatRefundReq;
import com.amumu.drama.common.modules.sumapay.dto.req.WeChatSingleOrderQueryReq;
import com.amumu.drama.common.modules.sumapay.dto.resp.WeChatPaySuccessResp;
import com.amumu.drama.common.modules.sumapay.dto.resp.WeChatRefundResp;
import com.amumu.drama.common.modules.sumapay.tools.MD5Tools;
import com.amumu.drama.common.modules.yipay.config.YipayConfig;
import com.amumu.drama.common.modules.yipay.constat.DeviceTypeEnum;
import com.amumu.drama.common.modules.yipay.constat.YipayTypeEnum;
import com.amumu.drama.common.modules.yipay.dto.req.YipaySubmitReq;
import com.amumu.drama.common.modules.yipay.dto.resp.YipayOrderResp;
import com.amumu.drama.common.modules.yipay.service.YipayService;
import com.amumu.drama.common.utils.HttpUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * @author sunzhuang
 * @date 2024/6/19 10:25
 * @slogan 天下风云出我辈, 一入代码岁月催
 * @desc todo
 */
@Service
public class YipayServiceImpl implements YipayService {


    @Autowired
    private YipayConfig yipayConfig;

    /**
     * 创建订单
     *
     * @param request
     */
    @Override
    public YipayOrderResp createOrder(YipaySubmitReq request) {
        //创建支付订单
        request.setPid(yipayConfig.getPid());
        request.setType(YipayTypeEnum.WXPAY.getCode());
        request.setNotify_url(yipayConfig.getNotifyUrl());
        request.setReturn_url("");
        if (StrUtil.isBlank(request.getDevice())) {
            request.setDevice(DeviceTypeEnum.PC.getCode());
        }
        request.setClientip(yipayConfig.getClientIp());
        request.setSignType(yipayConfig.getSignType());
        TypeReference<Map<String, String>> reference = new TypeReference<Map<String, String>>() {
        };
        Map<String, String> map = JSONUtil.parseObj(request).toBean(reference);
        String sign = MD5Tools.generateYiPaySign(map, yipayConfig.getKey());
        request.setSign(sign);

        YipayOrderResp yipayOrderResp = HttpUtils.doPost(yipayConfig.getYipayUrl(), request, YipayOrderResp.class);

        return yipayOrderResp;
    }

    /**
     * 单笔订单查询
     *
     * @param request
     */
    @Override
    public WeChatPaySuccessResp singleQuery(WeChatSingleOrderQueryReq request) {
        return null;
    }

    /**
     * 退款
     *
     * @param request
     */
    @Override
    public WeChatRefundResp refund(WeChatRefundReq request) {
        return null;
    }
}
